package com.evoupsight.monitorpass.gateway.handlers;

import com.evoupsight.monitorpass.gateway.handlers.codec.Message;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
@Qualifier("serverMessageHandler")
@ChannelHandler.Sharable
public class ServerMessageHandler extends ChannelInboundHandlerAdapter {
    private static final Logger LOG = LoggerFactory.getLogger(ServerMessageHandler.class);

    //    @Override
//    public void channelReadComplete(ChannelHandlerContext ctx) {
//        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
//    }
//
//    @Override
//    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        System.out.println();
//    }
//    @Override
//    public void handlerAdded(ChannelHandlerContext ctx) {
//        System.out.println("Handler added");
//    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object message) throws Exception {
        Message msg = (Message) message;
        System.out.println("消息魔数0是:" + msg.getMagicNumber0());
        System.out.println("消息魔数1是:" + msg.getMagicNumber1());
        System.out.println("消息魔数2是:" + msg.getMagicNumber2());
        System.out.println("消息魔数3是:" + msg.getMagicNumber3());
        System.out.println("消息版本是:" + msg.getVersion());
        System.out.println("消息长度是:" + msg.getLength());
        System.out.println("消息体是:" + msg.getBody());
        ctx.write("ok");
        ctx.channel().close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        LOG.debug("Channel is active");
        super.channelActive(ctx);
        ctx.channel().read();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        LOG.debug("Channel is disconnected");
        //NettyChannelMap.remove((SocketChannel) ctx.channel());
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        System.out.println(cause.getMessage());
        super.exceptionCaught(ctx, cause);
    }
}
